package top.lyf1210.yuwenrpcspringbootstarter.bootstrap;

import com.yuwen.RpcApplication;
import com.yuwen.yuwenRPC.config.RegistryConfig;
import com.yuwen.yuwenRPC.config.RpcConfig;
import com.yuwen.yuwenRPC.model.ServiceMetaInfo;
import com.yuwen.yuwenRPC.registry.LocalRegistry;
import com.yuwen.yuwenRPC.registry.Registry;
import com.yuwen.yuwenRPC.registry.RegistryFactory;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import top.lyf1210.yuwenrpcspringbootstarter.annotation.RpcService;

/**
 * @ClassNameRpcProviderBootstrap
 * @Description TODO
 * @Author钰玟
 * @Date2025/4/6 下午3:17
 * @Version 1.0
 **/

public class RpcProviderBootstrap implements BeanPostProcessor {
    /**
     * Bean 初始化后执行
     * @param bean bean
     * @param beanName name
     * @return return Value
     * @throws BeansException exception
     */
    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        /**
         * 获取所有注册了得Bean
         */
        Class<?> beanClass = bean.getClass();
        /**
         * 判断是否有 RpcService注解 ，无 =》 null
         */
        RpcService rpcService = beanClass.getAnnotation(RpcService.class);//@top.lyf1210.yuwenrpcspringbootstarter.annotation.RpcService(serviceVersion="1.0", interfaceClass=void.class)
        if(rpcService != null){
            //需要注册的服务
//            1. 获取服务的元信息
            Class<?> interfaceClass = rpcService.interfaceClass();
            //默认值处理
            if(interfaceClass==void.class){
                interfaceClass = beanClass.getInterfaces()[0];
            }
            String serviceName = interfaceClass.getName();
            String serviceVersion = rpcService.serviceVersion();
            //2. 注册服务
            //本地注册
            LocalRegistry.registry(serviceName,beanClass);

            //全局配置
            final RpcConfig  rpcConfig = RpcApplication.getRpcConfig();
            //注册到注册中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getRegistry(registryConfig.getRegistryType());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceVersion(serviceVersion);
            serviceMetaInfo.setServiceHost(rpcConfig.getHost());
            serviceMetaInfo.setServicePort(rpcConfig.getPort());
            try {
                registry.register(serviceMetaInfo);
            } catch (Exception e) {
                throw new RuntimeException(serviceName+"服务注册失败",e);
            }
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);

    }
}
